from QQLoginTool.QQtool import OAuthQQ
from django.shortcuts import render
from django.conf import settings
# Create your views here.
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from oauth.models import OAuthQQUser
from oauth.serializers import OauthSerializers


class OauthLoginView(CreateAPIView):
    '''
    构建qq登陆的链接
    '''
    def get(self, request):

        # 1.获取前段  state
        state = request.query_params.get('next', None)
        # 2.前段没有传递state，自己手动制定
        if state is None:
            state = '/'
        # 3.初始化oauthqq对象
        qq = OAuthQQ(client_secret=settings.QQ_CLIENT_SECRET, client_id=settings.QQ_CLIENT_ID,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=state)
        # 4.构建qq登陆页面的跳转链接
        login_url = qq.get_qq_url()
        # 5.返回结果
        return Response({
            'login_url': login_url
        })


class OauthView(CreateAPIView):
    '''
    获取openid
    '''
    serializer_class = OauthSerializers

    def get(self, request):
        # 1.获取code
        code = request.query_params.get('code', None)
        # 2.判断前段传递的有code值
        if code is None:
            return Response({'errors': '缺少code值'}, status=400)
        # 3.通过code值获取access——token
        qq = OAuthQQ(client_secret=settings.QQ_CLIENT_SECRET, client_id=settings.QQ_CLIENT_ID,
                     redirect_uri=settings.QQ_REDIRECT_URI, state='/')
        access_token = qq.get_access_token(code)
        # 4.通过access——token获取openip
        openid = qq.get_open_id(access_token)

        # 5.判断openid是否被绑定过
        try:
            # 6.查询openid所对应的数据是否存在
            qq_suer = OAuthQQUser.objects.get(openid=openid)
        except:
            # 7.不存在则进入绑定页面
            tjs = TJS(settings.SECRET_KEY, 300)
            open_id = tjs.dumps({'openid': openid}).decode()
            return Response({'access_token': open_id})
        else:
            # 8.存在则用户登陆成功
            # 9.生成token值，实现状态保持
            user = qq_suer.user

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            return Response({
                    'token': token,
                    'username': user.username,
                    'user_id': user.id
                })

    # def post(self, request):
    #     '''
    #     获取openid和绑定openid
    #     '''
    #
    #     # 1.获取验证码
    #     # 2.验证数据
    #     # 3.保存数据
    #     # 4.返回结果






